﻿using OpenAuth.Domain;
using OpenAuth.Domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenAuth.Repository
{
    /// <summary>
    /// ④仓储层内实现领域层定义的仓储接口，对应webpai的webconfig的autofac映射
    /// ，下面是配置webapi的webconfig的autofac映射关系
    /// </summary>
    public class SortRepository : BaseRepository<Sort>, ISortRepository
    {
        /// <summary>
        /// 分页获取类别
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public IEnumerable<Sort> LoadSorts(int pageindex, int pagesize)
        {
            return Context.Sorts.OrderBy(u => u.Id).Skip((pageindex - 1) * pagesize).Take(pagesize);
        }
        /// <summary>
        /// 通过IDs获取类别
        /// </summary>
        /// <param name="sortIds"></param>
        /// <returns></returns>
        public IEnumerable<Sort> LoadInSorts(params Guid[] sortIds)
        {
            var result = from sort in Context.Sorts
                         where sortIds.Contains(sort.Id)
                         select sort;
            return result;

        }
        /// <summary>
        /// 获取类别条数
        /// </summary>
        /// <param name="sortIds"></param>
        /// <returns></returns>
        public int GetSortCntInSorts(params Guid[] sortIds)
        {
            return LoadInSorts(sortIds).Count();
        }
        /// <summary>
        /// 分页获取类别数据
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="sortIds"></param>
        /// <returns></returns>
        public IEnumerable<Sort> LoadInSorts(int pageindex, int pagesize, params Guid[] sortIds)
        {
            return LoadInSorts(sortIds).OrderBy(u => u.Id).Skip((pageindex - 1) * pagesize).Take(pagesize);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        public void Delete(Guid id)
        {
            Delete(u => u.Id == id);
        }

        /// <summary>
        /// 获取当前节点的所有下级节点ID
        /// </summary>
        public Guid[] GetSubIds(Guid sortId)
        {
            if (sortId == Guid.Empty)
            {
                return Find(null).Select(u => u.Id).ToArray();
            }
            var sort = FindSingle(u => u.Id == sortId);
            var ids = Find(u => u.CascadeId.Contains(sort.CascadeId)).Select(u => u.Id).ToArray();
            return ids;
        }
    }
}
